<!-- 确认费用 -->
<template>
  <a-modal
    width="65vw"
    :closable="false"
    v-model:visible="visible"
    :mask-closable="false"
    :esc-to-close="false"
    unmount-on-close
    @close="onCancel"
    class="modal-dialog-wrapper"
  >
    <template #title> 确认对账</template>
    <div class="fee-page">
      <div class="confirm-cost-content" v-for="(item, index) in feeList" :key="index">
        <ConfirmFeeItem :fee="item" />
      </div>
      <div class="total-cost">
        <div class="total-cost-title">合计</div>
        <div class="total-cost-value">
          <div>{{ costType == 0 ? '应收' : '应付' }}：{{ unitVal(Math.abs(feeCostAmount.receiveAmount), '元') }}</div>
          <div>{{ costType == 0 ? '待收' : '待付' }}：{{ unitVal(Math.abs(feeCostAmount.receivedNotAmount), '元') }}</div>
        </div>
      </div>
      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 40px; overflow: hidden">
        <page-form-row>
          <page-form-item
            field="paymentTime"
            :label="costName + '时间'"
            :rules="[{ required: true, message: '请选择' + costName + '时间', trigger: 'change' }]"
          >
            <i-date-picker class="w-full" v-model="form.paymentTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
          </page-form-item>

          <page-form-item
            field="paymentWay"
            :label="costName + '方式'"
            :rules="{ required: true, message: '请选择' + costName + '方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select placeholder="请选择" v-model="form.paymentWay" @change="typeChange" :disabled="disabledCostType">
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>

          <page-form-item
            field="account"
            :label="costName + '账号'"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择' + costName + '方式' : '请选择'"
              v-model="form.account"
              :disabled="!form.paymentWay ? true : false"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>

          <page-form-item
            field="actualAmount"
            :label="costName + '金额'"
            :rules="{ required: true, message: '请输入' + costName + '金额' }"
          >
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>

          <page-form-item field="customerId" label="客户名称" :rules="{ required: true, message: '请输入客户名称' }">
            <!-- 
            借调单-跨门店调车：下拉单选，下拉为操作人权限下所有的门店，默认展示确认费用时填写的信息
            借调单-借入/借出：下拉单选，下拉为商户下所有的同行名称，默认展示确认费用时填写的信息
          -->
            <remote-select
              popup-container=".confirm-cost-box"
              v-if="transferType == 0"
              v-model="form.customerId"
              placeholder="请选择客户名称"
              :params="{ siteType: 40, siteStatusList: [10] }"
              type="site_listBystaff"
              @change="changeCustomerBySite"
            />

            <remote-select
              popup-container=".confirm-cost-box"
              v-if="transferType == 1 || transferType == 2"
              v-model="form.customerId"
              placeholder="请选择客户名称"
              type="sameIndustry_list"
              @change="changeCustomerBySameIndustry"
            />
          </page-form-item>

          <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>

          <page-form-item field="settlementRemark" label="结算备注" size="2/3">
            <i-input placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onCancel">关闭</a-button>
        <a-button type="primary" :loading="loading" @click="submitFn">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  import ConfirmFeeItem from '@/views/assets/car/car-manage/components/comfirm-fee-item.vue'
  import { Message } from '@arco-design/web-vue'
  import { getConfirmFeeDetail, confirmFee } from '@/api/asset/carTransfer'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  const visible = ref(false)
  const loading = ref(false)
  const costType = ref(null) // type  0-收款，1-付款，3-收款&付款  (合计 正-收款  负-付款)
  const paywayEnum = ref([]) //收付款方式
  const accountList = ref([]) //收付款账号列表
  const form = ref({
    idList: [], //结算单ids
    carId: '',
  })
  const transferType = ref() // 借调类型
  const costName = ref(null)
  const feeList = ref([])
  const formRef = ref(null)
  const disabledCostType = ref(false)
  const onCancel = () => {
    visible.value = false
    formRef.value.resetFields()
    disabledCostType.value = false
    paywayEnum.value = []
    accountList.value = []
    loading.value = false
  }

  const emits = defineEmits(['confirm'])

  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        loading.value = true
        const param = {
          ...form.value,
        }
        confirmFee(param)
          .then(() => {
            Message.success('操作成功')
            loading.value = false
            visible.value = false
            formRef.value.resetFields()
            emits('confirm')
          })
          .catch(() => {
            loading.value = false
          })
      }
    })
  }

  const feeCostAmount = ref({})
  const open = (options, type) => {
    console.log(options, 'options')
    transferType.value = type
    if (type == 0) {
      form.value.customerType = 2
    } else {
      form.value.customerType = 0
    }
    form.value.idList = options instanceof Array ? options : [options]
    visible.value = true
    getConfirmFeeDetail({ idList: options instanceof Array ? options : [options] }).then((res) => {
      if (res.code == 200) {
        const result = res.result
        feeCostAmount.value = result
        feeList.value = result.carAssetFeeList
        form.value.actualAmount = Math.abs(result.receiveAmount) //固定金额，不可修改
        costType.value = res.result.costType
        form.value.paymentTime = feeList.value[feeList.value.length - 1].createTime
        form.value.customerId = feeList.value[feeList.value.length - 1].supplierId
        form.value.customerName = feeList.value[feeList.value.length - 1].supplierName
        form.value.customerAccount = result.receiveAccount
        form.value.customerType = feeList.value.length ? feeList.value[0].supplierType : undefined
        if (costType.value == 0) {
          costName.value = '收款'
        } else {
          costName.value = '付款'
        }
        // 押金抵扣为固定收付款方式
        if (feeCostAmount.value.payType != null) {
          disabledCostType.value = true
          form.value.paymentWay = feeCostAmount.value.payType.toString()
        } else {
          form.value.paymentWay = JSON.stringify(res.result.paymentWay)
        }
        getType()
      }
    })
  }

  // 收付款类型
  const getType = () => {
    getAccountByPageData({ type: costType.value }).then((res) => {
      // 过滤
      let data = res.result
      data.forEach((i) => {
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '5' && i.way != '-1' && disabledCostType.value) {
          paywayEnum.value.push(i)
        } else if (
          i.way != '1' &&
          i.way != '2' &&
          i.way != '3' &&
          i.way != '4' &&
          i.way != '5' &&
          i.way != '-1' &&
          !disabledCostType.value
        ) {
          paywayEnum.value.push(i)
        }
      })
      if (form.value.paymentWay) {
        typeChange(form.value.paymentWay)
      }
    })
  }

  // 账号
  const typeChange = (e) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: costType.value == 0 ? 0 : 1 }).then((res) => {
          accountList.value = res.result
        })
      }
    })
  }

  // 选择客户名称（门店）
  const changeCustomerBySite = (_, option = {}) => {
    form.value.customerName = option.siteName
  }
  // 选择客户名称（同行）
  const changeCustomerBySameIndustry = (_, option = {}) => {
    form.value.customerName = option.industryName
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  // 弹窗添加的样式
  .fee-page {
    position: relative;
    width: 100%;
    max-height: 70vh;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
  .confirm-cost-content {
    border: 1px solid #f2f3f5;
    padding: 20px;
  }
  .total-cost {
    height: 100px;
    background: #f2f3f5;
    opacity: 1;
    padding: 20px;
    font-size: 14px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    .total-cost-title {
      color: #1d2129;
    }
    .total-cost-value {
      color: #1890ff;
      div:nth-of-type(2) {
        margin-top: 16px;
      }
    }
  }
</style>
